package com.codemonkey.lq.qd.utils;

import org.apache.ibatis.scripting.xmltags.ExpressionEvaluator;
import org.apache.ibatis.scripting.xmltags.OgnlCache;

public final class ExpressionEvaluatorUtils {

	private static final ExpressionEvaluator DEFAULT = new ExpressionEvaluator();

	private ExpressionEvaluatorUtils() {
		super();
		throw new Error("does not initialize this class");
	}

	public static ExpressionEvaluator getInstance() {
		return DEFAULT;
	}

	// ------------------------------------------------------------------------------

	public static <T> T evaluateVal(String expression, Object parameterObject) {
		Object value = OgnlCache.getValue(expression, parameterObject);
		return (T) value;
	}

	public static boolean evaluateBoolean(String expression, Object parameterObject) {
		return ExpressionEvaluatorUtils.DEFAULT.evaluateBoolean(expression, parameterObject);
	}

	/**
	 * 执行一段Java代码; <br/>
	 * 注意目前不要在代码中使用泛型,俺还未找到对策
	 * @param <T> 执行完毕后返回值的类型
	 * @param expression Java代码的字符串形式;注意目前不要在代码中使用泛型,俺还未找到对策
	 * @param parameterObject Java代码执行时的Context
	 * @return
	 */
	public static <T> T callPieceOfCode(String expression, Object parameterObject) {
		String[] strArray = expression.trim().split(";");

		int len = strArray.length;
		for (int i = 0; i < strArray.length; i++) {
			String code = strArray[i];

			//如果最后一句话为return 语句;则提取相应的表达式进行OGNL评估
			if (i == len - 1 && code.contains("return")) { 
				String retu = code.replace("return", "");
				return (T) evaluateVal(retu, parameterObject);
			}

			evaluateVal(code, parameterObject);
		}

		return null;
	}
}
